
/**
 * AppleIIGo
 * Language Card class
 * (C) 2007-2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#include "LanguageCard.h"

LanguageCard::LanguageCard(Motherboard * motherboard,
						   char * slotDeviceName) :
SlotDevice(motherboard, slotDeviceName) {
	ramMemoryByteNum = LANGUAGECARD_BYTENUM;
}

void LanguageCard::onDevicesConnected() {
	SlotDevice::onDevicesConnected();
	mmu = motherboard->getMmu();
}

void LanguageCard::onMemoryRequested() {
	ramMemoryOffset = motherboard->getMemory()->requestMemory(ramMemoryByteNum);
}

void LanguageCard::onResetAsserted(bool isRestart) {
	if (!isRestart)
		return;
	
	setMemoryOffset();
	
	mmu->setLanguageCardBank2(true);
	mmu->enableLanguageCardRead(false);
	mmu->enableLanguageCardWrite(true);
	
	isPreWrite = false;
	
	UINT8 * ramMemory = motherboard->getMemory()->getMemory(ramMemoryOffset);
	for (UINT32 index = 0; index < ramMemoryByteNum; index++)
		ramMemory[index] = 0;
}

void LanguageCard::writeIo(UINT16 address, UINT8 value) {
	setMemoryOffset();
	
	mmu->setLanguageCardBank2(!(address & 8));
	
	if (!(address & 1))
		mmu->enableLanguageCardWrite(false);
	isPreWrite = false;
	
	mmu->enableLanguageCardRead(!(((address & 2) >> 1) ^ (address & 1)));
}

UINT8 LanguageCard::readIo(UINT16 address) {
	setMemoryOffset();
	
	mmu->setLanguageCardBank2(!(address & 8));
	
	if (address & 1) {
		if (isPreWrite)
			mmu->enableLanguageCardWrite(true);
	} else
		mmu->enableLanguageCardWrite(false);
	isPreWrite = (address & 1);
	
	mmu->enableLanguageCardRead(!(((address & 2) >> 1) ^ (address & 1)));
	
	return timingGenerator->readFloatingBus();
}

void LanguageCard::setMemoryOffset() {
	mmu->setLanguageCardMemory(ramMemoryOffset);
}
